package com.quanyue.music.file.controller;

import com.quanyue.auto.util.ServiceResult;
import com.quanyue.auto.web.Principal;
import com.quanyue.auto.web.Scope;
import com.quanyue.music.domain.constant.FMChannel;
import com.quanyue.music.domain.constant.UserRole;
import com.quanyue.music.domain.entity.ListenRecord;
import com.quanyue.music.domain.entity.UserSurvey;
import com.quanyue.music.file.mapper.ListenRecordMapper;
import com.quanyue.music.file.service.ExcelService;
import com.quanyue.music.file.service.StatisticsService;
import com.quanyue.music.file.service.SurveyService;
import com.quanyue.music.file.type.*;
import com.shzisg.mybatis.mapper.page.Page;
import com.shzisg.mybatis.mapper.page.PageRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Api(tags = "数据统计")
@Scope(role = UserRole.MANAGER)
@RestController
@RequestMapping("/api")
public class StatisticsController {
    @Autowired
    private StatisticsService statisticsService;
    @Autowired
    private ListenRecordMapper listenRecordMapper;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private SurveyService surveyService;

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @ApiOperation(value = "调查问卷列表")
    @PostMapping(value = "/survey/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Page <SurveyDetail>> surveyList(@RequestBody PageRequest request) {
        return ServiceResult.success(surveyService.findSurveyDetail(request));
    }

    @ApiOperation(value = "调查问卷导出")
    @GetMapping(value = "/survey/excel", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <String> surveyList() {
        return ServiceResult.success(surveyService.surveyExcel());
    }

    @ApiOperation(value = "添加调查问卷")
    @Scope(role = UserRole.USER)
    @PostMapping(value = "/survey/add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Boolean> addSurvey(@RequestBody UserSurvey userSurvey,
                                             @ApiIgnore Principal principal) {
        surveyService.addSurvey(userSurvey, principal.getId());
        return ServiceResult.SUCCESS;
    }

    @ApiOperation(value = "删除调查问卷")
    @DeleteMapping(value = "/survey/delete", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Boolean> deleteSurvey(@RequestParam("id") String id) {
        surveyService.deleteSurvey(id);
        return ServiceResult.SUCCESS;
    }


    @ApiOperation(value = "点赞/收听人数数量统计")
    @PostMapping(value = "/like/statistics", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Page <FMDetailLikeResult>> likeCountRanking(@RequestBody FMDetailLikeRequest request) {
        return ServiceResult.success(statisticsService.findLikeCount(request));
    }

    @ApiOperation(value = "峰值统计")
    @PostMapping(value = "/hot/statistics", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <FMHotResult>> hotRanking(@RequestBody HotStatisticsRequest request) {
        return ServiceResult.success(statisticsService.findHot(request));
    }

    @ApiOperation(value = "更新实时在线人数")
    @Scope(role = UserRole.USER)
    @Transactional
    @PostMapping(value = "/real/time/people/update", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Boolean> updatePeoples(@RequestBody ListenRecordRequest recordRequest,
                                                 @ApiIgnore Principal principal) {
        List <ListenRecord> list = listenRecordMapper.findByDetail(recordRequest.getFmId(), principal.getId(), recordRequest.getFmChannel(), recordRequest.getZoneType());
        ListenRecord check;
        if (list.isEmpty()) {
            check = null;
        } else {
            if (list.size() > 1) {
                Collection <String> deleteList = new ArrayList <>();
                for (int i = 1; i < list.size(); i++) {
                    deleteList.add(list.get(i).getId());
                }
                listenRecordMapper.deleteAll(deleteList);
            }
            check = list.get(0);
        }
        if (check != null) {
            long a = check.getModifyTime().until(LocalDateTime.now(), ChronoUnit.SECONDS);
            log.info("距离上次更新过了多少秒: {}", a + "用户ID: " + principal.getId());
            check.setDelFlag(false);
            check.setModifyTime(LocalDateTime.now());
            listenRecordMapper.updateSelective(check);
            listenRecordMapper.updateDelFlag(check.getId(), check.getUserId());
        } else {
            ListenRecord listenRecord = new ListenRecord();
            listenRecord.setFmId(recordRequest.getFmId());
            listenRecord.setUserId(principal.getId());
            listenRecord.setChannel(recordRequest.getFmChannel());
            listenRecord.setZoneType(recordRequest.getZoneType());
            listenRecord.setCreateTime(LocalDateTime.now());
            listenRecord.setModifyTime(LocalDateTime.now().plusSeconds(10 + (int) Math.random() * 59));
            listenRecord.setDelFlag(false);
            listenRecordMapper.insert(listenRecord);
            int count = listenRecordMapper.updateDelFlag(listenRecord.getId(), listenRecord.getUserId());
            log.info("当前时间是: {}", LocalDateTime.now() + "更新了几条数据:" + count);
        }
        return ServiceResult.SUCCESS;
    }

    @ApiOperation(value = "实时在线人数查询")
    @GetMapping(value = "/real/time/people/select", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <ListenRecordResult>> findPeoples() {
        List <ListenRecordResult> listenRecordResults = listenRecordMapper.findByChannel();
        if (listenRecordResults == null) listenRecordResults = Collections.EMPTY_LIST;
        return ServiceResult.success(listenRecordResults);
    }

    @ApiOperation(value = "数据导出Excel表")
    @PostMapping(value = "/export/excel/file", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <String> export(@RequestBody ExcelFileRequest request) {
        return ServiceResult.success(excelService.exportFile(request));
    }

    @ApiOperation(value = "频道Excel数据统计")
    @GetMapping(value = "/export/channel/excel/file", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <String> exportChannel(@RequestParam("date") String date,
                                                @RequestParam("fmChannel") FMChannel fmChannel) {
        return ServiceResult.success(excelService.exportChannelFile(date, fmChannel));
    }
}
